var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');

var app = getApp();

Page({
  data: {
    vipCard: {},
    vipCardNumber: "",
    status: 0
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getVipCard();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getVipCard();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getVipCard: function () {
    let that = this;
    that.setData({
      vipCard: {},
      status: 0
    });
    util.request(api.VipCardMy).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          status: res.data.status,
          vipCard: res.data.vipCard
        });
        let userInfo = wx.getStorageSync('userInfo')
        if (res.data.status == 0){
          userInfo.vipCardId = 0
        }else{
          userInfo.vipCardId = res.data.vipCard.id
        }
        wx.setStorageSync('userInfo', userInfo)
      }
    });

  },
  bindVipCardNumber: function (e) {
    this.setData({
      vipCardNumber: e.detail.value
    });
  },
  clearVipCardNumber: function () {
    this.setData({
      vipCardNumber: ''
    });
  },
  goBindVipCardNumber: function () {
    if (this.data.vipCardNumber.length === 0) {
      util.showErrorToast("请输入会员卡号");
      return;
    }

    let that = this;
    util.request(api.BindVipCard, {
      vipCardNumber: that.data.vipCardNumber
    }, 'POST').then(function (res) {
      if (res.errno === 0) {
        that.getVipCard();
        that.clearVipCardNumber();
        wx.showToast({
          title: "绑定会员卡成功",
          duration: 2000
        })
      }
      else {
        util.showErrorToast(res.errmsg);
      }
    });
  },
  unBindVipCard: function(){
    let that = this;
    util.request(api.UnBindVipCard, {}, 'POST').then(function (res) {
      if (res.errno === 0) {
        that.getVipCard();
        wx.showToast({
          title: "解除会员卡成功",
          duration: 2000
        })
      }
      else {
        util.showErrorToast(res.errmsg);
      }
    });
  }
})